$(document).ready(function () {

    // 初始化日期选择器
    $('#datepicker').datepicker({
        format: 'yyyy-mm-dd', // 设置日期格式
        autoclose: true,      // 自动关闭日历
        todayHighlight: true  // 高亮今天的日期
    });

    $('#datepicker2').datepicker({
        format: 'yyyy-mm-dd',  // 设置日期格式
        autoclose: true,       // 自动关闭日历
        todayHighlight: true   // 高亮今天的日期
    });

    // 点击图标也可以打开日历
    $('.search-icon').click(function () {
        var inputId = $(this).siblings('input').attr('id');
        $('#' + inputId).datepicker('show');  // 显示对应输入框的日期选择器
    });

    // 点击输入框时也会弹出日期选择器
    $('#datepicker1, #datepicker2').click(function () {
        $(this).datepicker('show');
    });

    // 点击输入框或图标时，显示选择器
    $('#peopleInput, .search-icon').click(function () {
        $('#peopleSelector').toggle();  // 切换显示/隐藏选择器
    });
	
	
	
	
	//预订之后的跳转
		$(".book").click(function() { 
			var roomtypeId = $(this).attr("id");
			var check_time = $("#checkinDate").val();
			var leave_time = $("#checkoutDate").val();
	
			window.location.href = 'details2.html?roomId=' + roomtypeId + '&check_time=' + check_time +
				'&leave_time=' + leave_time;
		})

})


// 获取当前日期并格式化为 YYYY-MM-DD
    const today = new Date();
    const formattedToday = today.toISOString().split('T')[0];

    // 获取入住和离店日期的输入元素
    const checkinDateInput = document.getElementById("checkinDate");
    const checkoutDateInput = document.getElementById("checkoutDate");

    // 设置入住日期默认值为今天，并且设置最小日期为今天
    checkinDateInput.value = formattedToday;
    checkinDateInput.min = formattedToday;

    // 设置离店日期的最小值为入住日期的下一天，并且默认离店日期为明天
    const defaultCheckoutDate = new Date(today);
    defaultCheckoutDate.setDate(today.getDate() + 1); // 默认离店日期为明天
    checkoutDateInput.value = defaultCheckoutDate.toISOString().split('T')[0];
    checkoutDateInput.min = defaultCheckoutDate.toISOString().split('T')[0];

    // 当入住日期改变时，自动更新离店日期的最小值
    checkinDateInput.addEventListener("change", function() {
        const checkinDate = new Date(checkinDateInput.value);
        const checkoutDate = new Date(checkinDate);
        checkoutDate.setDate(checkinDate.getDate() + 1); // 离店日期应该至少是入住日期之后的一天
        
        // 更新离店日期输入框的最小值和默认值
        checkoutDateInput.min = checkoutDate.toISOString().split('T')[0];
        if (new Date(checkoutDateInput.value) < checkoutDate) {
            checkoutDateInput.value = checkoutDate.toISOString().split('T')[0]; // 如果当前离店日期小于最小值，设为最小值
        }
    });
	
	//点击导航条添加样式
	$(function(){
		$('.nav-item').click(function(){
			$(this).children().addClass('active');
			$(this).siblings('li').children().removeClass('active')
		})
	})
	
	
	//添加登录
	window.onload = function() {
	    var nickname = sessionStorage.getItem("nickname");
	    
	    if (nickname) {
	        // 如果有昵称，替换登录注册的链接
	        document.querySelector('.user-account').innerHTML = `
	            <span>Hello! ${nickname}</span>/
	            <a href="#" id="logout">退出登录</a>
	        `;
			
			  // 添加点击事件来处理退出登录
			        document.getElementById('logout').addEventListener('click', function(event) {
			            event.preventDefault();  // 阻止默认的链接跳转
			            sessionStorage.removeItem("nickname");  // 清除昵称
			            window.location.href = "login.html";  // 跳转到登录页面
			        });
			    }
	    
};


//渲染页面中的数据
  // 获取 URL 中的 flag 参数
   const urlParams = new URLSearchParams(window.location.search);

  
  const hotelId = urlParams.get('hotelId');
  const checkTime = urlParams.get('checkTime');
  const leaveTime = urlParams.get('leaveTime');
  

$.ajax({
	url:'http://localhost:8080/hotel/findHotelListById',
	async:false,
	type:"get",
	data:{'hotelId':hotelId},
	success:function(rs){
	if(rs.code === 2001){
		var result = rs.t;
		$(".content").html(result.hotel_name);
		$(".first").html(result.city_location + result.region_location + result.hotel_address);
		$(".info_score").html(result.hotel_score+"不错！");
		$(".address").html(result.city_location+result.province_location);
		$(".detail-info").html(result.city_location + result.hotel_address+result.province_location);
		
		var sheshi = result.facilities;
		
		for(let i =0 ; i< sheshi.length;i ++){
			$(".iconlist").empty();
			
			var sheshiinfo = `<div class="icon">
                            <img src="./static/image/detail/005.png" alt="">
                            <div class="icon-name">`+sheshi[i].facilityInfo+`</div>
                        </div>`
						
				$(".iconlist").append(sheshiinfo);		
		}
	$(".review-score-value").html(result.hotel_score);	
		
	}
	}
	
})

$.ajax({
    url: 'http://localhost:8080/hotel/findRoomTypeById',
	async:false,
    type: "get",
    data: { 'hotelId': hotelId, 'checkTime': '11-17', 'leaveTime': '11-18' },
    success: function (rs) {
		if(rs.code === 2001){			
		
			$(".room-list-wrap").empty(); // 确保选择器正确

			var result = rs.t || []; // 确保 result 是一个数组
			// alert(result)   //list集合
			// console.log(result);

			for(let i =0 ; i< result.length;i ++){
				var roomType = result[i].room_type || "未知房型"; // 安全处理空数据
				var haveMeal = result[i].have_meal ? "含早" : "不含早";
				var price = result[i].price || 0;
				var originalPrice = price + 10;
				var roomFacilityList = result[i].facilities;
				// console.log(roomFacilityList);
				var facilityInfoString = '';
				if(roomFacilityList.length == 0){
					facilityInfoString = '暂无设施信息';
				} 
				// 遍历 result 数组
				for (let i = 0; i < roomFacilityList.length; i++) {
				    // 访问当前设施对象的 facilityInfo 字段
				    var facilityInfo = roomFacilityList[i].facilityInfo;
				    // 将设施信息添加到字符串中，可以使用逗号或其他分隔符
					
				    facilityInfoString += facilityInfo + ' ';
				}
				// console.log(roomList);
				// alert(roomList.length);
				var raw = `
					<div class="room-list-box">
						<div class="recommend-card">
							<div class="room-sigle-img">
								<div class="recommend">
									<img src="./static/image/detail/hand-thumbs-up.svg" alt="">
									优选推荐
								</div>
								<div class="room-img">
									<img src="./static/image/detail/room-img.jpg">
								</div>
							</div>
							<div class="divider-y"></div>
							<div class="room-card">
								<div>
									<div class="rec-card">
										<div class="content-flex">
											<div class="rpitem">
												<div class="room-card-cn">
													<div class="top">
														<h1 class="items-center">
															${roomType}
															<img src="./static/image/detail/chevron-right.svg">
														</h1>
													</div>
												</div>
												<h2>
													<span class="produce-name">
														<div class="food-hover-wrap">
															<span>${haveMeal}</span>
														</div>
													</span>
													<span class="dot"></span>
													<span class="cancel-text">入住日18点前免费取消</span>
												</h2>
												<div class="info">
													${facilityInfoString}
												</div>
											</div>
											<div class="right" style="z-index: unset;">
												<div class="price">
													<div class="price-text mb-1-5">
														<p style="text-wrap: nowrap;">
															<span class="original-price">${originalPrice}</span>
															<span class="currency">￥</span>${price}
														</p>
													</div>
													<div class="price-text">
														<div class="discount">
															<em class="font-500">特惠红包等1项</em>
															优惠￥10
															<img src="./static/image/detail/chevron-right.svg" class="upward-icon">
														</div>
													</div>
												</div>
												<div class="right-content">
													<div class="items-end">
														<div class="btn">
															<div class="btn-top" style="line-height: 48px;">
																<a style="color:#fff;" class="book" id=` + result[i].id + `>预订</a>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>`;
				
				$(".room-list-wrap").append(raw);
								
				if( roomFacilityList.length !=0 ){
					for(let i =0 ; i< roomFacilityList.length;i ++){
						// alert("循环");
						
						var facilities = roomFacilityList[i].facilities || []; // 确保设施存在
						var facilityInfo = facilities.length > 0 ? facilities.map(f => f.facilityInfo).join(", ") : "暂无设施信息";
					}
					
					
				}
					
				}
				 // 确保选择器正确
			// });
		}else{
			alert("bbbbbb ")
		}
    },
    error: function (err) {
        console.error("请求失败", err);
    }
});




$.ajax({
    url: 'http://localhost:8080/hotel/findAssessById',
	async:false,
    type: "get",
    data: { 'hotelId': hotelId, 'checkTime': '11-17', 'leaveTime': '11-18' },
    success: function (rs) {
        if (rs.code === 2001) {
            $(".assess").empty();
            var result = rs.t;
            console.log(result);

            for (let i = 0; i < result.length; i++) {
                // 处理 assess_date 转换为日期
                const timestamp = result[i].assess_date;
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;

    //             处理 assess_image 转换为图片 HTML
				const imagePaths = result[i].assess_image.split(';'); // 拆分图片路径
				let imageHTML = ''; // 用于存储图片 HTML
				console.log(imagePaths); // 使用 console.log 而不是 alert

				imagePaths.forEach((path, index) => { // 将 3 替换为 index
					imageHTML += `
						<img class="img-item" src="${path}" 
							 alt="图片${index + 1}" 
							 style="width: 112px; height: 112px; margin: 8px; object-fit: cover;">`;
				});

                // 拼接 raw 内容
                var raw = `
                    <div class="common-item">
                        <div class="item-top">
                            <div class="user-info">
                                <img class="user-img" src="./static/image/detail/user.svg">
                                <div class="user-nd">
                                    <text class="user-name">${result[i].user_nickname}</text>
                                    <text class="IP-text">IP:天津市</text>
                                    <div>
                                        <text class="user-detail">${result[i].room_type}</text>
                                    </div>
                                </div>
                            </div>
                            <div class="item-score-text">
                                <div class="item-score">${result[i].score}</div>
                                <div class="item-text">超棒</div>
                            </div>
                        </div>
                        <div class="item-center">
                            <h3>${result[i].assess_info}</h3>
                        </div>
                        <div class="comment-image">
                           ${imageHTML}
                        </div>
                        <div class="comment-item-detail">
                            <div class="comment-item-time">
                                <text>${formattedDate} 已入住</text>
                            </div>
                        </div>
                    </div>`;
                
                // 将生成的 raw 插入到页面中
                $(".assess").append(raw);
            }
        }
    }
});

	
